package com.example.testuser.service.impl;

import com.example.testuser.entity.TestUser;
import com.example.testuser.repository.UserRepository;
import com.example.testuser.service.TestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class TestUserServiceImpl implements TestUserService {

    private UserRepository userRepository;

    @Autowired
    public TestUserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<TestUser> getAllUser() {
        return userRepository.findAll();
    }

    @Override
    public TestUser getUserByPk(String pkUser) {
        return userRepository.findById(pkUser).orElse(null);
    }

    @Override
    public TestUser getUserByCodeOrName(String code, String name) {
        return userRepository.findByCodeOrName(code, name);
    }

    @Override
    public void addOrUpdateUser(TestUser user) {
        userRepository.save(user);
    }

    @Override
    public void deleteUser(TestUser user) {
        userRepository.delete(user);
    }

    @Override
    public void deleteUserByPk(String pkUser) {
        userRepository.deleteById(pkUser);
    }

    @Override
    public List<TestUser> findListMySql(String identity) {
        return userRepository.findListMySql(identity);
    }

    @Override
    public List<?> getAllStreamUser() {
        Stream<?> streamAllUsers = userRepository.streamAllUsers();
        return streamAllUsers.collect(Collectors.toList());
    }

    @Override
    public List<TestUser> getAllStreamUser1() {
        return userRepository.streamAllUsers1().collect(Collectors.toList());
    }

    @Override
    public List<TestUser> getAllStreamUser2() {
        return userRepository.streamAllBy().collect(Collectors.toList());
    }

    @Override
    public List<TestUser> readAllBy() throws InterruptedException, ExecutionException {
        CompletableFuture<List<TestUser>> future = userRepository.readAllBy();
        CompletableFuture.supplyAsync(this::getAllStreamUser);
        return future.get();
    }

}
